package com.android.tiango.baba.act;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.BaseEntity;
import com.android.tiango.baba.entity.IndexHotTopicsEntity;
import com.android.tiango.baba.entity.SimpleProductModel;
import com.android.tiango.baba.entity.SimpleProductTopicEntity;
import com.android.tiango.baba.entity.SimpleProductTopicModel;
import com.android.tiango.baba.entity.SimpleTopicModel;
import com.android.tiango.baba.entity.SimpleUserModel;
import com.android.tiango.baba.entity.UserModel;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.ImageLoader;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.TimeToUtil;
import com.android.tiango.baba.view.AppTitleBar;
import com.android.tiango.baba.view.PullListView;
import com.android.tiango.baba.view.PullListView.PullListViewListener;

/**
 * 我的收藏
 * @author txg
 * 
 */
public class ActZoeCollection extends BaBaseActivity implements PullListViewListener,   OnClickListener {
	private PullListView mLv_ActpPost, mLv_TopicPost;
	private Button mBtnActPost, mBtnTopicPost;
	private  HashMap<Integer, Boolean> mActCheckMap,mTopicMap;
	private ArrayList<SimpleProductTopicModel> mActData;
	private ArrayList<SimpleTopicModel> mTopicData;
	private ActAdapter mActAdapter;
	private TopicAdapter mTopicAdapter;
	private boolean mIsDel = false;
	private  int mPageIndex = 0;
	private  int mPageIndex_Topic = 0;
	private String mActParDels = "";
	private String mTopicParDels = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_myzoe_collect);
		findView();
		setListener();
	}

	private void findView() {
		mImageLoader=new ImageLoader(this, R.drawable.ic_default);
		//活动
		mLv_ActpPost = (PullListView) findViewById(R.id.lv_actpost);
		mLv_ActpPost.setHeaderDividersEnabled(false);
		mLv_ActpPost.setFooterDividersEnabled(false);
		mLv_ActpPost.setSelector(android.R.color.transparent);
		mActAdapter = new ActAdapter(ActZoeCollection.this); 
		mLv_ActpPost.setAdapter(mActAdapter);
		mLv_ActpPost.setPullListener(this); 
		mLv_ActpPost.startOnRefresh(); 
		//话题
		mLv_TopicPost = (PullListView) findViewById(R.id.lv_topicpost);
		mLv_TopicPost.setHeaderDividersEnabled(false);
		mLv_TopicPost.setFooterDividersEnabled(false);
		mLv_TopicPost.setSelector(android.R.color.transparent); 
		mLv_TopicPost.setPullListener(new PullListViewListener() {
			public void onPullRefresh() {
				mPageIndex_Topic = 1;
				doMyCollPost(1);
			}

			public void onPullLoadMore() {
				mPageIndex_Topic += 1;
				doMyCollPost(1);
			}
		}); 
		//按钮处理
		mBtnActPost = (Button) findViewById(R.id.btnactpost);
		mBtnTopicPost = (Button) findViewById(R.id.btntopicpost);
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		mImageLoader = new ImageLoader(this, R.drawable.img_loading_default);
		if (null != mTitleBar) {
			mTitleBar.setTitle("我的收藏");
			mTitleBar.setImageBackGround(R.drawable.bg_title_blue);
			mTitleBar.setBackIcon(R.drawable.icon_back);
			mTitleBar.setMoreText(getResources().getString(R.string.s_edit));
			mTitleBar.setMoreTextOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(!mIsDel){
						mTitleBar.setMoreText(getResources().getString(R.string.s_delete));
						mIsDel = true;
						if(mLv_ActpPost.getVisibility() == View.VISIBLE){
							//活动
							if(mActData == null || mActData.size() == 0){
								return;
							}
							mActAdapter.notifyDataSetChanged();
							mActCheckMap = new HashMap<Integer, Boolean>();
							for (int i = 0; i < mActData.size(); i++) {
								mActCheckMap.put(i, false);
							}
						}else if(mLv_TopicPost.getVisibility() == View.VISIBLE ){
							//话题
							if(mTopicData == null || mTopicData.size() == 0){
								return;
							}
							mTopicAdapter.notifyDataSetChanged();
							mTopicMap = new HashMap<Integer, Boolean>();
							for (int i = 0; i < mTopicData.size(); i++) {
								mTopicMap.put(i, false);
							}
						}
					}else{ 
						if(mLv_ActpPost.getVisibility() == View.VISIBLE){
							if(!StringUtils.isEmpty(mActParDels)) { 
								mActParDels = mActParDels.substring(0, mActParDels.length() -1);
								doDelColl(0);
							}else{
								Toast.makeText(ActZoeCollection.this, "请选择删除项!", Toast.LENGTH_LONG).show();
							}
						}else if(mLv_TopicPost.getVisibility() == View.VISIBLE ){
							if(!StringUtils.isEmpty(mTopicParDels)) {
								//进行删除操作
								mIsDel = false;
								mTopicParDels = mTopicParDels.substring(0, mTopicParDels.length() -1);
								doDelColl(1);
							}else{
								Toast.makeText(ActZoeCollection.this, "请选择删除项!", Toast.LENGTH_LONG).show();
							}
						}
					}
				}
			});
			setBackOnClickListener();
		}
	}

	protected void doDelColl(final int type) { 
		String token = ShareCookie.getToken();
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", token);
		httpParams.put("collectType", type);
		String s = type == 1 ? mTopicParDels : mActParDels ;
		httpParams.put("topicId", s); 
		client.post(HttpUrl.getUrl(HttpUrl.DeleteMyFavoriteTopic), httpParams,
				new HttpCallBack() {
					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						dismissWaitingDialog();
						if (!StringUtils.isEmpty(arg1)) {
							Toast.makeText(ActZoeCollection.this, arg1, Toast.LENGTH_LONG).show();
						}
					}
					public void onHttpStarted() {
						showWaitingDialog("请稍后...");
					}
					@Override
					public void onHttpSuccess(Object arg0) {
						dismissWaitingDialog(); 
						BaseEntity entity = (BaseEntity)arg0;
						if(entity.getState() == 1){
							mTitleBar.setMoreText(getResources().getString(R.string.s_edit));
							Toast.makeText(ActZoeCollection.this, "删除成功!", Toast.LENGTH_LONG).show();
							if(type == 0 && mLv_ActpPost != null){ 
								mLv_ActpPost.startOnRefresh();
								mActParDels = "";
							}else if(type == 1 && mLv_TopicPost != null){
								mLv_TopicPost.startOnRefresh();
								mTopicParDels = "";
							}
							//进行删除操作
							mIsDel = false;
						}
					}
		},BaseEntity.class);
		
	}

	private void setListener() {
		mBtnActPost.setOnClickListener(this);
		mBtnTopicPost.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnactpost:
			// 活动贴
			mActParDels = ""; 
			mBtnActPost.setBackgroundResource(R.drawable.bg_toptitlebtn);
			mBtnTopicPost.setBackgroundResource(R.drawable.bg_toptitlebtn_pressed);
			mLv_ActpPost.setVisibility(View.VISIBLE);
			mLv_TopicPost.setVisibility(View.GONE);
			mIsDel = false;
			mTitleBar.setMoreText(getResources().getString(R.string.s_edit)); 
			if (mActAdapter == null) {
				mLv_ActpPost.startOnRefresh();
			}else{
				mActAdapter.notifyDataSetChanged();
			}
			break;
		case R.id.btntopicpost:
			// 话题贴
			mTopicParDels = "";
			mIsDel = false;
			mTitleBar.setMoreText(getResources().getString(R.string.s_edit));
			mBtnTopicPost.setBackgroundResource(R.drawable.bg_toptitlebtn_left);
			mBtnActPost.setBackgroundResource(R.drawable.bg_toptitlebtn_pressed_left);
			mLv_ActpPost.setVisibility(View.GONE);
			mLv_TopicPost.setVisibility(View.VISIBLE);
			if (mTopicAdapter == null) {
				mTopicAdapter = new TopicAdapter(ActZoeCollection.this); 
				mLv_TopicPost.setAdapter(mTopicAdapter);
				mLv_TopicPost.startOnRefresh();
			} else {
				mTopicAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	} 
	
	@Override
	public void onPullRefresh() {
		mPageIndex = 1;
		doMyCollPost(0);
	}
	
	@Override
	public void onPullLoadMore() {
		mPageIndex += 1;
		doMyCollPost(0); 
	}

	private void doMyCollPost(int type) {
		UserModel model = ShareCookie.getUserInfo();
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", model.getToken());
		httpParams.put("collectType", type);
		if(type == 0){
		httpParams.put("pageIndex", mPageIndex);
		}else{
		httpParams.put("pageIndex", mPageIndex_Topic);
		}
		httpParams.put("pageSize", Constants.PAGE_SIZE);
		if(type == 0){
			//0-活动贴
			client.get(HttpUrl.getUrl(HttpUrl.MYFAVORITETOPICS), httpParams, new HttpCallBack() {
				public void onHttpFailure(Exception arg0, String arg1) { 
					if (!StringUtils.isEmpty(arg1)) {
						Toast.makeText(ActZoeCollection.this, arg1, Toast.LENGTH_LONG).show();
					} 
				}

				public void onHttpStarted() {
				}

				public void onHttpSuccess(Object arg0) {
					//活动帖子
					SimpleProductTopicEntity entity = (SimpleProductTopicEntity)arg0;
					mActData = entity.getData();
					if(mActData != null && mActData.size() > 0 ){
						if(mActAdapter != null){
							mActAdapter.setData(mActData);
							mActAdapter.notifyDataSetChanged();
						}else{
							mActAdapter = new ActAdapter(ActZoeCollection.this);
							mActAdapter.setData(mActData);
							mLv_ActpPost.setAdapter(mActAdapter);
						}
					}else{
						mActAdapter = new ActAdapter(ActZoeCollection.this);
						mLv_ActpPost.setAdapter(mActAdapter);
						mActAdapter.notifyDataSetChanged();
						Toast.makeText(ActZoeCollection.this, R.string.s_notdata, Toast.LENGTH_LONG).show();
					}
					mLv_ActpPost.onRefreshFinish();
					mLv_ActpPost.onLoadFinish();
					
				} 
			},SimpleProductTopicEntity.class);
		}else if(type == 1){
			//1-话题贴
			client.get(HttpUrl.getUrl(HttpUrl.MYFAVORITETOPICS), httpParams, new HttpCallBack() {
				public void onHttpFailure(Exception arg0, String arg1) { 
					if (!StringUtils.isEmpty(arg1)) {
						Toast.makeText(ActZoeCollection.this, arg1, Toast.LENGTH_LONG).show();
					}
				}

				public void onHttpStarted() { 
				}

				public void onHttpSuccess(Object arg0) { 
					//话题贴
					IndexHotTopicsEntity entity = (IndexHotTopicsEntity)arg0;
					mTopicData = entity.getData();
					if(mTopicData != null && mTopicData.size() > 0 ){
						if(mTopicAdapter != null){
							mTopicAdapter.setData(mTopicData);
							mTopicAdapter.notifyDataSetChanged();
						}else{
							mTopicAdapter = new TopicAdapter(ActZoeCollection.this);
							mTopicAdapter.setData(mTopicData);
							mLv_TopicPost.setAdapter(mTopicAdapter);
						}
					}else{
						mTopicAdapter = new TopicAdapter(ActZoeCollection.this);
						mLv_TopicPost.setAdapter(mTopicAdapter);
						mTopicAdapter.notifyDataSetChanged();
						Toast.makeText(ActZoeCollection.this, R.string.s_notdata, Toast.LENGTH_LONG).show();
					}

					mLv_TopicPost.onRefreshFinish();
					mLv_TopicPost.onLoadFinish();
				} 
			}, IndexHotTopicsEntity.class);
		} 
	}
	
	//活动帖
	class ActAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private ArrayList<SimpleProductTopicModel> data;
		
		public ActAdapter(Context context) {
			inflater = LayoutInflater.from(context);
			if(data == null){
				data = new ArrayList<SimpleProductTopicModel>();
			}
		}

		public void setData(ArrayList<SimpleProductTopicModel> data){
			this.data = data;
		}
		
		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public SimpleProductTopicModel getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final ActItemTag tag;
			if (convertView == null) {
				tag = new ActItemTag();
				convertView = inflater.inflate(R.layout.item_topicpost, null);
				tag.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
				tag.tv_date = (TextView) convertView.findViewById(R.id.tv_date); 
				tag.tv_actcomments = (TextView) convertView.findViewById(R.id.tv_actcomments);
				tag.tv_acttoview = (TextView) convertView.findViewById(R.id.tv_acttoview); 
				tag.iv_brandimg = (ImageView) convertView.findViewById(R.id.iv_brandimg);
				tag.iv_acthead = (ImageView) convertView.findViewById(R.id.iv_acthead);
				tag.cb_delshare = (CheckBox) convertView.findViewById(R.id.cb_delshare);
				//ly_bghead 
				convertView.setTag(tag);
			} else {
				tag = (ActItemTag) convertView.getTag();
			} 
			final SimpleProductTopicModel product = getItem(position);
			if(product != null){
				//商品帖子
				SimpleProductModel spm = product.getSimpleProduct();
				if(spm != null){
					//商品
					tag.tv_title.setText(spm.getProductName());
					//暂时 。。mImageLoader.loadImage(spm.getProductImage().getImageUrl(), tag.iv_brandimg);
				}
				tag.tv_actcomments.setText(product.getReplyNumber()+"");
				tag.tv_acttoview.setText(product.getReadNumber()+"");
				tag.tv_date.setText(TimeToUtil.getSystemTimeSetFormat(product.getStartTime(), TimeToUtil.ACCURATE_TO_THE_DAY));
				if (mIsDel) {
					tag.cb_delshare.setVisibility(View.VISIBLE);
					tag.cb_delshare.setChecked(mActCheckMap.get(position));
				}else{
					tag.cb_delshare.setVisibility(View.GONE);
				}
				convertView.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
		                if(mIsDel){
		                	ActItemTag tag = (ActItemTag) v.getTag();
			                boolean check = tag.cb_delshare.isChecked();
			                if(check){
			                	 mActCheckMap.put(position, false);
			                	 mActParDels = mActParDels.replace(product.getTopicId() + "," , "");
			                }else{
			                	 mActCheckMap.put(position, true);
			                	 mActParDels +=  product.getTopicId() + ",";
			                }
			                tag.cb_delshare.setChecked(mActCheckMap.get(position));
		                }else{
							if (null != product) {
								Intent intent = new Intent(ActZoeCollection.this, ActActiveDetail.class);
								intent.putExtra("BarId", product.getBarId());
								intent.putExtra("TopicId", product.getTopicId());
								startActivity(intent);
							}
		                }
					}
				}); 
			}
			return convertView;
		}

		public class ActItemTag {
			TextView tv_title;
			TextView tv_date;
			TextView tv_actcomments;
			TextView tv_acttoview; 
			ImageView iv_brandimg; 
			ImageView iv_acthead;
			CheckBox cb_delshare;
		}

	}
	
	//话题帖
	class TopicAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private ArrayList<SimpleTopicModel> data;
		private Context context;
		public TopicAdapter(Context context) {
			this.context = context;
			inflater = LayoutInflater.from(context);
			if(data == null){
				data = new ArrayList<SimpleTopicModel>();
			}
		}
		
		public void setData(ArrayList<SimpleTopicModel> data) {
			this.data = data;
		}


		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public SimpleTopicModel getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final ItemTag tag ;
			if (convertView == null) {
				tag = new ItemTag();
				convertView = inflater.inflate(R.layout.item_actpost, null);
				tag.tv_actinfo = (TextView) convertView.findViewById(R.id.tv_actinfo) ;
				tag.cb_delshare = (CheckBox) convertView.findViewById(R.id.cb_delshare)  ;
				tag.iv_acthead = (ImageView) convertView.findViewById(R.id.iv_acthead)  ;
				tag.tv_acttitle = (TextView) convertView.findViewById(R.id.tv_acttitle)  ;
				tag.tv_acttime = (TextView)  convertView.findViewById(R.id.tv_acttime) ;
				tag.iv_sex = (ImageView)  convertView.findViewById(R.id.iv_sex) ;;
				tag.iv_thelord = (ImageView) convertView.findViewById(R.id.iv_thelord)  ;
				tag.iv_actre = (ImageView) convertView.findViewById(R.id.iv_actre)  ;
				tag.iv_actj = (ImageView)  convertView.findViewById(R.id.iv_actj) ;
				tag.iv_actd = (ImageView) convertView.findViewById(R.id.iv_actd)  ; 
				tag.tv_actcomments = (TextView) convertView.findViewById(R.id.tv_actcomments)  ;
				tag.tv_acttoview = (TextView)  convertView.findViewById(R.id.tv_acttoview) ;
				convertView.setTag(tag);
			} else {
				tag = (ItemTag) convertView.getTag();
			}
			final SimpleTopicModel model = getItem(position);
			if(model != null){
				SimpleUserModel userm = model.getSimpleUser();
				if(userm != null){
					tag.tv_acttitle.setText(userm.getNickName());//用户名
					mImageLoader.loadImage(userm.getAvatarUrl(), tag.iv_acthead);//头像
					int gender = userm.getGender();//性别
					if(gender == 1){
						tag.iv_sex.setImageDrawable(getResources().getDrawable(R.drawable.bg_sex));
					}else if(gender == 2){
						tag.iv_sex.setImageDrawable(getResources().getDrawable(R.drawable.bg_sex_girl));
					}
				}
				tag.tv_acttime.setText(TimeToUtil.getSystemTimeSetFormat(model.getCreateTime(), TimeToUtil.ACCURATE_TO_THE_DAY));//时间
				//吧主
				if(model.getIsBarOwner() == 0){
					tag.iv_thelord.setVisibility(View.GONE);
				}else{
					tag.iv_thelord.setVisibility(View.VISIBLE);
				}
				tag.tv_actinfo.setText(model.getTopicName()); //内容
				tag.tv_actcomments.setText(model.getReadNumber()+"");//查看数
				tag.tv_acttoview.setText(model.getReplyNumber()+"");//回帖数
			
				if (mIsDel) {
					tag.cb_delshare.setVisibility(View.VISIBLE);
					tag.cb_delshare.setChecked(mTopicMap.get(position));
				}else{
					tag.cb_delshare.setVisibility(View.GONE);
				}
				convertView.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
		                if(mIsDel){
		                	ItemTag tag = (ItemTag) v.getTag();
			                boolean check = tag.cb_delshare.isChecked();
			                if(check){
			                	mTopicParDels = mTopicParDels.replace(model.getTopicId() + ",", "");
			                	mTopicMap.put(position, false);
			                }else{
			                	mTopicParDels += model.getTopicId() + ",";
			                	mTopicMap.put(position, true);
			                }
			                tag.cb_delshare.setChecked(mTopicMap.get(position));
		                }else{
		                	Intent intent = new Intent(context, ActCardDetail.class);
		    				intent.putExtra(Constants.BARID, model.getBarId());
		    				intent.putExtra(Constants.TOPICID, model.getTopicId());
		    				intent.putExtra(Constants.BARNAME, model.getBarName());
		    				context.startActivity(intent);
		                }
					}
				}); 
			}
			return convertView;
		}

		private class ItemTag {
			TextView tv_actinfo;
			CheckBox cb_delshare;
			ImageView iv_acthead;
			TextView tv_acttitle;
			TextView tv_acttime;
			ImageView iv_sex;;
			ImageView iv_thelord;
			ImageView iv_actre;
			ImageView iv_actj;
			ImageView iv_actd; 
			TextView tv_actcomments;
			TextView tv_acttoview;
		}
	}
}
